import { useEffect, useRef } from 'react';
import { initModel } from 'src/libs/topology/g6';
import {mapNodeStatusType, processOwnParallelEdges} from "../../../libs/topology/util";

export interface GraphRenderNode {
    id: string;
    label: string;
}

interface GraphRenderEdge {
    source: string;
    target: string;
}

interface graphDataSource {
    nodes: GraphRenderNode[];
    edges: GraphRenderEdge[];
}

export interface TopologyProps {
    styles?: Record<string, string>;
    dataSource: graphDataSource;
    dataIndex?: string;
}

export function mapNodeData(data: any, edges: any[] = []) {
    const res = [];

    for(const node of data) {
        let item;
        const nameObj = node.attributes.find(a => a.attributeClassificationId === 'inst_name');
        // 不显示业务
        if(node.modelClassificationId === 'biz') continue;

        const attrs: any = {};

        for(const attr of node.attributes) {
            attrs[attr.attributeName] = attr.attributeValue;
        }

        item = {
            id: node.id + '',
            apmId: node.apmId,
            label: nameObj.attributeValue,
            icon: node.icon || 'default',
            modelClassificationId: node.modelClassificationId,
            attributes: attrs,
            type: mapNodeStatusType(node.runningStatus).type,
            status: node.runningStatus
        };

        let exist = false;
        for(const edge of edges) {
            if(edge.source === item.id || edge.target === item.id) {
                exist = true;
            }
        }

        if(node.nodes && node.nodes.length > 1) {
            item.instances = [];
            // 集群模式
            for(const instance of node.nodes) {
                const instanceNode = {
                    id: instance.id + '',
                    label: instance.ip,
                    icon: 'cluster',
                    modelClassificationId: 'cluster',
                    apmId: node.apmId,
                };
                item.instances.push(instanceNode);
            }

            item.type = 'cluster';
        } else {
            item.type = 'model';
        }

        res.push(item);
    }

    return res;
}

export function mapEdgeData(data: any[]) {
    const edges = data.map(item => {
        const {srcModelInstance, desModelInstance, modelRelation} = item;
        const newItem: any = {
            source: (item?.srcModelInstanceId|| srcModelInstance.id) + '',
            target: (item?.desModelInstanceId || desModelInstance.id) + '',
            srcName: srcModelInstance?.name || '',
            desName: desModelInstance?.name || '',
            id: item.id + '',
            label: modelRelation.relationType.name,
            constraintCondition: item.constraintCondition,
            remark: item.remark,
            relationTypeId: item.relationTypeId,
            style: {
                endArrow: false,
                startArrow: false
            }
        };

        // 增加箭头显示
        if(item.modelRelation.relationType.directionType === 'SRC_TO_DES') {
            newItem.style.endArrow = true;
        }

        if(item.modelRelation.relationType.directionType === 'TWO_WAY') {
            newItem.style.endArrow = true;
            newItem.style.startArrow = true;
        }

        // loop
        if(newItem.source === newItem.target) {
            newItem.type = 'loop';
        }

        return newItem;
    });
    const egs = processOwnParallelEdges(edges);
    return egs;
}

export default function Topology(props: TopologyProps) {
    const { styles, dataSource } = props;
    const ref = useRef<HTMLDivElement>(null);
    // @ts-ignore
    dataSource.edges.push(mock[0]);
    const edges = mapEdgeData(dataSource.edges); // mapEdgeData(dataSource.edges)
    const nodes = mapNodeData(dataSource.nodes, edges); //

    useEffect(() => {
        const graph = initModel(ref.current);
        const renderData = {nodes, edges};
        graph.data(renderData);
        graph.render();
    }, [dataSource]);

    return <div ref={ref} style={styles} id={"topoInstance"}/>;
}
